package cn.wolfcode.trip.web.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.RegionQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/region")
public class RegionController {
    @Autowired
    private IRegionService service;

    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") RegionQueryObject qo) {
        List<Region> roots = service.selectList(qo);
        model.addAttribute("roots", roots);
        return "region/list";
    }

    @RequestMapping("/queryTreeView")
    @ResponseBody
    public Object queryTreeView(RegionQueryObject qo) {
        List<Region> menus = service.selectList(qo);
        if (qo.isTreeView()) {
            List<Map<String, Object>> treeMaps = new ArrayList<>();
            for (Region menu : menus) {
                Map<String, Object> treeMap = menu.toTreeView();
                treeMaps.add(treeMap);
            }
            return treeMaps;
        }

        return menus;
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Region region) {
        JSONResult json = new JSONResult();
        try {
            service.saveOrUpdate(region);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark("操作失败");
        }
        return json;

    }
}
